package com.mrper.asm

import com.mrper.asm.click.ViewClickMethodAdapter
import com.mrper.asm.click.ViewClickMethodDetectAdapter
import com.mrper.asm.click.ViewClickRecordPool
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.tree.MethodNode

/** 全局类的探访器 **/
class GlobalClassVisitor @JvmOverloads constructor(
    api: Int,
    classVisitor: ClassVisitor? = null
) : ClassVisitor(api, classVisitor) {

    override fun visit(version: Int, access: Int, name: String?, signature: String?, superName: String?, interfaces: Array<out String>?) {
        super.visit(version, access, name, signature, superName, interfaces)
        println("【class】：$name\nsignature=$signature\nsuperName=$superName\ninterfaces=$interfaces\n\n")
    }

    override fun visitMethod(access: Int, name: String?, descriptor: String?, signature: String?, exceptions: Array<out String>?): MethodVisitor {
        val mv = cv.visitMethod(access, name, descriptor, signature, exceptions)
        return if (ViewClickRecordPool.isClickMethod(name, descriptor, access)) {
            println("【Method】：$name\ndescriptor = $descriptor\nsignature = $signature\ninterfaces = $exceptions\n\n")
            ViewClickMethodAdapter(api, mv, access, name, descriptor, false)
        } else if (ViewClickRecordPool.isClickLambdaMethod(name, descriptor, access, ViewClickRecordPool.clickLambdaMethodLookup)) {
            println("【Method】：$name\ndescriptor = $descriptor\nsignature = $signature\ninterfaces = $exceptions\n\n")
            ViewClickMethodAdapter(api, mv, access, name, descriptor, true)
        } else {
            val methodNode = MethodNode(api, access, name, descriptor, signature, exceptions)
            ViewClickMethodDetectAdapter(api, mv, access, name, descriptor, methodNode)
        }
    }

}